package com.zhiwang.xiaoqu.download

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.bus.AppDownLoadProgressEvent
import installIntent
import org.greenrobot.eventbus.EventBus
import java.io.File

@SuppressLint("StaticFieldLeak")
object FileDownLoadManager {

    val TAG = "FileDownLoadManager"

    //url -> progress
    var downloadProgressMap = hashMapOf<String, Int>()

    //url -> taskid
    var downloadIdMap = hashMapOf<String, Int>()

    var nameUrlMap = hashMapOf<String, String>()

    // url  -> filename
    var nameMap = hashMapOf<String, String>()

    lateinit var context: Context

    fun holdContext(ctx: Context) {
        context = ctx
    }

    fun download(url: String, name: String, dir: String) {

        val id = FileDownloader.getImpl()
            .create(url)
            .setPath(
                File(
                    dir, name.plus(".apk")
                ).absolutePath, false
            )
            .setCallbackProgressTimes(15)
            .setListener(object : FileDownloadListener() {

                override fun warn(task: BaseDownloadTask) {

                }

                override fun completed(task: BaseDownloadTask) {
                    val event = AppDownLoadProgressEvent(
                        progress = "100", name = name
                            ?: "unknown"
                    )
                    event.apkFile = File(task.path)
                    EventBus.getDefault().post(event)
                    context.startActivity(event.apkFile?.installIntent(context))
                }

                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

                }

                override fun error(task: BaseDownloadTask, e: Throwable?) {
                    CrashReport.postCatchedException(e)
                }

                override fun started(task: BaseDownloadTask) {
                    //下载开始，开始记录 进度
                    downloadProgressMap[url] = 0
                    nameUrlMap[name] = url
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    val progress = Math.round(soFarBytes.toFloat() / totalBytes * 100)

                    if (BuildConfig.DEBUG)
                        Log.i(TAG, "progress: $progress")

                    downloadProgressMap[url] = progress
                    EventBus.getDefault().post(
                        AppDownLoadProgressEvent(
                            progress = progress.toString(), name = name
                                ?: ""
                        )
                    )
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {

                }

            })
            .start()

        downloadIdMap[url] = id

    }

    private fun getFileNameWithUrl(url: String): String? {
        if (url.endsWith(".apk") && url.lastIndexOf('/') != -1) {
            return url.substring(url.lastIndexOf('/') + 1)
        }

        //取后五个字符组成的字符串作为 文件名
        return url.substring(url.length - 5, url.length).plus(".apk")
    }


    /**
     * 暂停
     */
    fun pause(url: String) = FileDownloader.getImpl().pause(downloadIdMap[url] ?: -2)

    fun pause(id: Int) {
        FileDownloader.getImpl()
            .pause(id)
    }

    /**
     * 获取指定 app 的下载进度
     */
    fun getAppDownloadProgress(appName: String): String {
        return downloadProgressMap[nameUrlMap[appName]]?.toString() ?: "0"
    }

}